package com.bruce.controller;

import com.bruce.Common.Result;
import com.bruce.Common.Resultcode;
import com.bruce.bean.Course;
import com.bruce.bean.Courseplan;
import com.bruce.bean.Dto.CourseplanDto;
import com.bruce.bean.Dto.SelectCourseDto;
import com.bruce.bean.Student;
import com.bruce.bean.Teacher;
import com.bruce.service.CourseService;
import com.bruce.service.MajorService;
import com.bruce.service.TeacherService;
import com.bruce.service.impl.CourseServiceImpl;
import com.bruce.service.impl.MajorServiceImpl;
import com.bruce.service.impl.TeacherServiceImpl;
import com.bruce.utils.PageUtils;
import com.mysql.cj.xdevapi.Session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/teacherServlet.do")
public class TeacherServlet extends HttpServlet {

    TeacherService teacherService = new TeacherServiceImpl();
     CourseServiceImpl courseService= new CourseServiceImpl();
     MajorService majorService= new MajorServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        String method = req.getParameter("flag");
        HttpSession session = req.getSession();
        String syscode = (String) session.getAttribute("syscode"); //系统生成验证码
        switch (method){
            case "login":
                Login(req, resp, syscode,session);
                break;
            case "add":
                teacherADD(req,resp);
                break;
            case "addTeacheCourse":
                SelectTeacherCourse(req, resp);
                break;
            case "SelectTeacheCourseTodoaddcou":
                SelectTeacheCourseTodoaddcou(req, resp);
                break;
            case "InsertCourse":
                InsertCourse(req, resp);
                break;
            case "ManageTeachedCourse":
                ManageTeachedCourse(req, resp, session);
                break;

            case "toUpdateTeacheCourse":
                toUpdateTeacheCourse(req, resp);
                break;
            case "UpdataCourse":
                UpdataCourse(req, resp);
            case "checkCourseAndstudentList":
                checkCourseAndstudentList(req, resp, session);
                break;
            case "studentList":
                studentList(req, resp, session);
            case "scorePage":
                socre(req, resp, session);
                break;
            case "addGrade":
                String cid = req.getParameter("cid");
                String sid = req.getParameter("sid");
                String grade = req.getParameter("grade");
                Result addcourse =null;
                try {
                  addcourse   = majorService.addcourse(Integer.parseInt(grade), cid, sid);
                }catch (RuntimeException e){
                    req.setAttribute("msg", Resultcode.Update_err.getMess());
                    req.setAttribute("url","/teacherServlet.do?flag=scorePage&pageIndex=1&cid="+cid+"");
                    req.getRequestDispatcher("/fail.jsp").forward(req,resp);
                }
                req.setAttribute("msg",Resultcode.System_success.getMess());
                req.setAttribute("url","/teacherServlet.do?flag=scorePage&pageIndex=1&cid="+cid+"");
                req.getRequestDispatcher("/success.jsp").forward(req,resp);
                break;
            case "logout":
                session.invalidate(); //session失效
                resp.sendRedirect("login.jsp");
        }

    }

    private void socre(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws ServletException, IOException {
        String pageIndex = req.getParameter("pageIndex");
        String cid = req.getParameter("cid");
        String tid = (String)session.getAttribute("tid");
        PageUtils<Student> studentPageUtils = courseService.FindStudentbyTeacheIdAndCourseId(tid, cid, pageIndex);
        Course cname = courseService.findClassname(Integer.parseInt(cid));

        req.setAttribute("cid",cid);
        req.setAttribute("cname",cname.getCname());
        req.setAttribute("pageUtilsEndCourse",studentPageUtils);
        req.getRequestDispatcher("/teacher/endCourse.jsp").forward(req,resp);
    }

    private void studentList(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws ServletException, IOException {
        String pageIndex = req.getParameter("pageIndex");
        String cid = req.getParameter("cid");
        String tid = (String) session.getAttribute("tid");
        PageUtils<Student> studentPageUtils = courseService.FindStudentbyTeacheIdAndCourseId(tid, cid, pageIndex);
        Course cname = courseService.findClassname(Integer.parseInt(cid));
        req.setAttribute("cname",cname.getCname());
        req.setAttribute("pageUtilsList",studentPageUtils);
        req.getRequestDispatcher("/teacher/printStudent.jsp").forward(req,resp);
    }

    private void checkCourseAndstudentList(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws ServletException, IOException {
        String pageIndex = req.getParameter("pageIndex");
        String tid = (String)session.getAttribute("tid");
        PageUtils<SelectCourseDto> pageUtils = courseService.FindSelecdCourse(tid, pageIndex);
        req.setAttribute("pageUtilsCheck",pageUtils);
        req.getRequestDispatcher("/teacher/serchSC.jsp").forward(req,resp);
    }

    private void UpdataCourse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Courseplan doAddcouForm = getDoAddcouForm(req);
        try {
            courseService.UpdataCourse(doAddcouForm);
        }catch (RuntimeException e){
            req.setAttribute("msg", Resultcode.Update_err.getMess());
            req.setAttribute("url","/teacherServlet.do?flag=ManageTeachedCourse&pageIndex=1");
            req.getRequestDispatcher("/fail.jsp").forward(req,resp);
        }
        req.setAttribute("msg",Resultcode.System_success.getMess());
        req.setAttribute("url","/teacherServlet.do?flag=ManageTeachedCourse&pageIndex=1");
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

    private void toUpdateTeacheCourse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cid = req.getParameter("cid");
        Courseplan courseplan = courseService.FindCourse(Integer.parseInt(cid));
        req.setAttribute("cplan",courseplan);
        req.getRequestDispatcher("/teacher/modCouPlan.jsp").forward(req,resp);
    }

    private void ManageTeachedCourse(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws ServletException, IOException {
        String pageIndex = req.getParameter("pageIndex");
        String tid = (String) session.getAttribute("tid");
        PageUtils<CourseplanDto> courseplanDtoPageUtils = courseService.FindCourseByTeacheid(tid, Integer.parseInt(pageIndex));
        req.setAttribute("pageUtilsCourse",courseplanDtoPageUtils);
        req.getRequestDispatcher("/teacher/manageCourse.jsp").forward(req,resp);
    }

    private void SelectTeacheCourseTodoaddcou(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cid = req.getParameter("cid");
        //先查询该课程是否有教师教 (false 表示没有老师 true表示有老师)
        boolean b = teacherService.FindIsTeacheCoursed(cid);
        if (b){
            req.setAttribute("msg", Resultcode.Teacher_ovload.getMess());
            req.setAttribute("url","/teacherServlet.do?flag=addTeacheCourse&pageIndex=1");
            req.getRequestDispatcher("fail.jsp").forward(req,resp);
        }else {
            req.setAttribute("cid",cid);
            req.getRequestDispatcher("/teacher/doAddCou.jsp").forward(req,resp);
        }
    }

    private void InsertCourse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Courseplan doAddcouForm = getDoAddcouForm(req);
        try {
            courseService.InsertIntoCoursepla(doAddcouForm);
        }catch (RuntimeException e){
            req.setAttribute("msg", Resultcode.Add_Error.getMess());
            req.setAttribute("url","/teacherServlet.do?flag=addTeacheCourse&pageIndex=1");
            req.getRequestDispatcher("/fail.jsp").forward(req,resp);
        }
        req.setAttribute("msg",Resultcode.System_success.getMess());
        req.setAttribute("url","/teacherServlet.do?flag=addTeacheCourse&pageIndex=1");
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

    private Courseplan getDoAddcouForm(HttpServletRequest req) {
        String courseclass = req.getParameter("courseclass");
        String[] coursetimestemp = req.getParameterValues("coursetime");
        String coursetimes = String.join(",", coursetimestemp);
        String[] courseweekstemp = req.getParameterValues("courseweek");
        String courseweeks = String.join(",",courseweekstemp);
        String cid = req.getParameter("cid");
        String tid = req.getParameter("tid");
        String classroom = req.getParameter("classroom");
        String creditstemp = req.getParameter("credits");
        int credits = Integer.parseInt(creditstemp);
        String periodstemp = req.getParameter("period");
        int periods = Integer.parseInt(periodstemp);
        String totalnumtemp = req.getParameter("totalnum");
        int totalnum = Integer.parseInt(totalnumtemp);
        Courseplan courseplan = new Courseplan(courseclass, coursetimes, courseweeks, cid, tid, classroom, credits, periods, totalnum);
        return courseplan;
    }

    private void SelectTeacherCourse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageIndex = req.getParameter("pageIndex");
        PageUtils pageUtils = new PageUtils();
        pageUtils.setPageIndex(Integer.parseInt(pageIndex));
        pageUtils.setPagesize(5);
        PageUtils<Course> coursePageUtils = courseService.FindALlCourse(pageUtils);
        req.setAttribute("pageUtils",coursePageUtils);
        req.getRequestDispatcher("/teacher/addCou.jsp").forward(req,resp);
    }

    private void Login(HttpServletRequest req, HttpServletResponse resp, String syscode, HttpSession session) throws IOException, ServletException {
        String tid = req.getParameter("tid");
        String tpassword = req.getParameter("tpassword");
        String usercode = req.getParameter("usercode"); //用户输入验证码
        if (syscode.equalsIgnoreCase(usercode)) {
            //封装
            Teacher t = new Teacher(tid, tpassword);
            //调用登录
            Teacher teacherLogin = teacherService.teacherLogin(t);
            if (teacherLogin != null) {
                session.setAttribute("tname",teacherLogin.getTname());
                session.setAttribute("tid",teacherLogin.getTid());
                resp.sendRedirect("/teacher/teacherFace.jsp");
            } else {
                req.setAttribute("msg", "账号或密码错误!");
                req.setAttribute("role", "teacher");
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        }else{
            req.setAttribute("msg", "验证码错误!");
            req.setAttribute("role", "teacher");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    private void teacherADD(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String tid = req.getParameter("tid");
        String tname = req.getParameter("tname");
        String tpassword = req.getParameter("tpassword");
        String tsex = req.getParameter("tsex");
        String introduction = req.getParameter("introduction");
        Teacher teacher = new Teacher(tid, tname, tpassword, tsex, introduction);
        try{
            teacherService.addTeacher(teacher);
            resp.getWriter().write("<script>alert('"+Resultcode.Add_succ.getMess()+"');location.href='/admin/addTeacher.jsp';</script>");
        }catch (Exception e){
            resp.getWriter().write("<script>alert('"+Resultcode.Add_Error.getMess()+"');location.href='/admin/addTeacher.jsp';</script>");
        }
    }
}
